package logic

import (
	"context"
	"fmt"
	"weekly/model/cache"
	"weekly/model/mysql"
	"weekly/pkg"

	"weekly/weeklyrpc/internal/svc"
	"weekly/weeklyrpc/weeklyrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LonginUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLonginUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LonginUserLogic {
	return &LonginUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LonginUserLogic) LonginUser(in *weeklyrpc.LonginUserRequest) (*weeklyrpc.LonginUserResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("account=?", in.Account).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("该用户不存在,请重新输入")
	}
	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("该密码不正确,请重新输入")
	}

	captcha, _ := cache.Rdb.Get(l.ctx, "CaptchaKey"+in.Account).Result()
	if in.Captcha != captcha {
		return nil, fmt.Errorf("图片验证码不正确,请重新输入")
	}
	smscaptcha, _ := cache.Rdb.Get(l.ctx, "SmsKey"+in.Account).Result()
	if in.SmsCaptcha != smscaptcha {
		return nil, fmt.Errorf("短信验证码不正确,请重新输入")
	}

	return &weeklyrpc.LonginUserResponse{
		UserId: int64(user.ID),
	}, nil
}
